/**
 * RC4密码
 */
public class RC4Cipher {
    byte [] sbox = new byte[256];
    byte [] keys = new byte[256];
    void initKey(byte [] key){
        for(int i = 0;i<256;i++){
            sbox[i]=(byte)i;
            keys[i]=key[i%key.length];
        }
        KSA();
    }
    void KSA(){
        byte temp;
        for(int i =0, j = 0;i<256;i++){
            j = (j + (sbox[i] & 0xff)+ (keys[i] & 0xff))%0xff;
            temp = sbox[i];
            sbox[i] = sbox[j];
            sbox[j] = temp;
        }
    }
    public byte[] encrypt(byte[] key, byte[] input){
        int i = 0, j = 0, t = 0;
        int k = 0;
        byte temp;
        byte[] output = new byte[input.length];
        initKey(key);
        for(k=0;k<input.length;k++){
            i = (i+1)%256;
            j = (j+(sbox[i] & 0xff))&0xff;
            temp = sbox[i];
            sbox[i] = sbox[j];
            sbox[j] = temp;
            t = ((sbox[i]&0xff)+(sbox[j]&0xff))&0xff;
            output[k] = (byte) (input[k] ^ sbox[t]);
        }
        return output;
    }
    public byte[] decrypt(byte[] key, byte[] input){
        return encrypt(key, input);
    }
    public String bytesToHex(byte[] bytes){
        StringBuilder sb = new StringBuilder();
        for(byte b : bytes){
            String hex = Integer.toHexString(b & 0xff);
            if(hex.length()<2){
                sb.append(0);
            }
            sb.append(hex);
        }
        return sb.toString();
    }
}